package com.cz.run.config.mvc;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @author CAIYJ
 * @Description: TODO()
 * @Date:2018/5/15 15:19
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    private static final Logger logger = LogManager
            .getLogger(WebConfig.class);

    @Value("${spring.images.path}")
    private String mImagesPath;

    /**
     * 添加拦截器
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // 验证权限拦截器
        registry.addInterceptor(loadMemberAccessHandlerInterceptor()).addPathPatterns("/news/**", "/product/**", "/sport/**", "/task/**", "/user/**", "/userPocket/**", "/userPocketLog/**");
        super.addInterceptors(registry);
    }

    // 权限管理
    @Bean
    AccessHandlerInterceptor loadMemberAccessHandlerInterceptor() {
        return new AccessHandlerInterceptor();
    }

    /**
     * 增加消息转换器，将返回消息中的 null 转成空字符串
     *
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MessageConverter());
        super.configureMessageConverters(converters);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (mImagesPath.equals("") || mImagesPath.equals("${spring.images.path}")) {
            String imagesPath = WebConfig.class.getClassLoader().getResource("").getPath();
            if (imagesPath.indexOf(".jar") > 0) {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            } else if (imagesPath.indexOf("classes") > 0) {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            mImagesPath = imagesPath;
        }
        logger.info("imagesPath=" + mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

}
